﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Pda_Total_Station;
using System.Collections;
using System.Threading;
using System.IO;

namespace SmartDeviceProject
{
    public partial class 平面位移观测 : Form
    {
        public 平面位移观测()
        {
            InitializeComponent();
            DataBase db = null;
            remoteId = Convert.ToInt32(ToolClass.GetProfileString("remoteid"));
            //连接自动观测的另一个数据库
            if (DataBase.ConnectToDataBase("", ref db, true))
            {
                m_db = db;
            }
            if (!m_db.IsTableInDataBase("projects"))
            {
                ArrayList list = new ArrayList();
                DataField fild = new DataField("time", "datetime", "not null");
                list.Add(fild);
                fild = new DataField("name", "nvarchar(50)", "not null");
                list.Add(fild);
                fild = new DataField("id", "integer", "not null");
                list.Add(fild);
                bool sucess = m_db.CreateNewTable("projects", list);
            }
            if (!m_db.IsTableInDataBase("stations"))
            {
                ArrayList list = new ArrayList();
                DataField fild = new DataField("time", "datetime", "not null");
                list.Add(fild);
                fild = new DataField("name", "nvarchar(50)", "not null");
                list.Add(fild);
                fild = new DataField("stationid", "integer", "not null");
                list.Add(fild);
                fild = new DataField("prjid", "integer", "not null");
                list.Add(fild);
                fild = new DataField("type", "nvarchar(50)", "not null");
                list.Add(fild);
                bool sucess = m_db.CreateNewTable("stations", list);
            }
            //m_db.DeleteTable("datalog");
            //储存结果数据
            if (!m_db.IsTableInDataBase("datalog"))
            {
                ArrayList list = new ArrayList();
                DataField fild = new DataField("id", "integer", "not null");
                list.Add(fild);
                fild = new DataField("name", "nvarchar(50)", "not null");
                list.Add(fild);
                fild = new DataField("Hz", "float", "not null");
                list.Add(fild);
                fild = new DataField("Hv", "float", "not null");
                list.Add(fild);
                fild = new DataField("slope", "float", "not null");
                list.Add(fild);
                fild = new DataField("E", "float", "not null");
                list.Add(fild);
                fild = new DataField("N", "float", "not null");
                list.Add(fild);
                fild = new DataField("H", "float", "not null");
                list.Add(fild);
                fild = new DataField("time", "datetime", "not null");
                list.Add(fild);
                bool sucess = m_db.CreateNewTable("datalog", list);
            }
            //学习配置点
            if (!m_db.IsTableInDataBase("dataconfig"))
            {
                ArrayList list = new ArrayList();
                DataField fild = new DataField("id", "integer", "not null");
                list.Add(fild);
                fild = new DataField("name", "nvarchar(50)", "not null");
                list.Add(fild);
                fild = new DataField("E", "float", "not null");
                list.Add(fild);
                fild = new DataField("N", "float", "not null");
                list.Add(fild);
                fild = new DataField("H", "float", "not null");
                list.Add(fild);
                bool sucess = m_db.CreateNewTable("dataconfig", list);
            }
        }

        #region 全局变量
        DataBase m_db;
        GeoCom geocom;
        svtps mytps;
        #endregion
        //pda数据库很奇怪,日期跟台式机格式不同.
        string datetime_str(DateTime time)
        {
            string str = time.ToString("M-d-yyyy HH:mm:ss");
            return str;
        }
        void copy_data()
        {
            string sql = "select * from dataconfig";
            DataTable dt ;//= m_db.GetDataSet(sql).Tables[0];
            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    sql = "insert into [dataconfig1] values(" + dt.Rows[i]["id"] + ",'"
            //        + dt.Rows[i]["name"] + "'," + dt.Rows[i]["E"] + ","
            //        + dt.Rows[i]["N"] + "," + dt.Rows[i]["H"] + ")";
            //    m_db.ExecuteSQL(sql);
            //}
            sql = "select * from datalog";
            dt = m_db.GetDataSet(sql).Tables[0];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sql = "insert into [datalog1] values(" + dt.Rows[i]["id"] + ",'"
                    + dt.Rows[i]["name"] + "'," + dt.Rows[i]["Hz"] + ","
                    + dt.Rows[i]["Hv"] + "," + dt.Rows[i]["slope"] + "," + dt.Rows[i]["E"] + ","
                     + dt.Rows[i]["N"] + "," + dt.Rows[i]["H"] + ",'" + datetime_str(Convert.ToDateTime(dt.Rows[i]["time"])) + "')";
                m_db.ExecuteSQL(sql);
            }
        }
        private void Load_Projects()
        {
            projectsView.Nodes[0].Nodes.Clear();
            string sql = "select [name],[id] from [projects]";
            DataTable dt = m_db.GetDataSet(sql).Tables[0];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string name = dt.Rows[i]["name"].ToString();
                TreeNode n = new TreeNode();
                n.Text = name;
                int prjid = Convert.ToInt32(dt.Rows[i]["id"]);
                sql = "select [name],[stationid] from [stations] where [prjid]=" +
                    prjid + " order by [stationid]";
                DataTable st = m_db.GetDataSet(sql).Tables[0];
                for (int j = 0; j < st.Rows.Count; j++)
                {
                    string stationName = st.Rows[j]["name"].ToString();
                    n.Nodes.Add(stationName);
                }
                projectsView.Nodes[0].Nodes.Add(n);
            }
        }


        #region 第一页
        //打开串口
        private void bConnect_Click(object sender, EventArgs e)
        {
            if (Combox.Text.Equals(string.Empty))
            {
                MessageBox.Show("请选择COM口");
                return;
            }
            try
            {
                string com = Combox.Text;
                if (geocom != null && geocom.port != null && geocom.port.IsOpen)
                {
                    geocom.port.Close();
                }
                geocom = new GeoCom(com);
                if (geocom.port != null)
                {
                    bConnect.Enabled = false;
                    bDisConnect.Enabled = true;
                }
            }
            catch (Exception a)
            {
                MessageBox.Show(a.Message);
            }
        }
        //关闭串口
        private void bDisConnect_Click(object sender, EventArgs e)
        {
            try
            {
                geocom.port.Close();
                bConnect.Enabled = true;
                bDisConnect.Enabled = false;
            }
            catch (Exception a)
            {
                MessageBox.Show(a.Message);
            }

        }

        //获取测站坐标
        private void btn_getstn_Click(object sender, EventArgs e)
        {
            string str = geocom.Get_Station();
            if (str != "0")
            {
                string[] v = str.Split(',');
                textBox1.Text = Math.Round(Convert.ToDouble(v[0]), 4).ToString();
                textBox2.Text = Math.Round(Convert.ToDouble(v[1]), 4).ToString();
                textBox3.Text = Math.Round(Convert.ToDouble(v[2]), 4).ToString();
                textBox4.Text = Math.Round(Convert.ToDouble(v[3]), 4).ToString();
            }
            else
            {
                MessageBox.Show("获取测站失败");
                return;
            }
            geocom.Open_Close_ATR("1");
            //geocom.Set_Measure_Mode("IO");
        }

        private void btnok1_Click(object sender, EventArgs e)
        {
            svpoint pt = new svpoint("center", Convert.ToDouble(textBox1.Text),
                Convert.ToDouble(textBox2.Text), Convert.ToDouble(textBox3.Text));
            double angle = Convert.ToDouble(txtzeroangle.Text);
            double d = Math.Floor(angle);
            double m = Math.Floor((angle - d) * 100);
            double s = (angle*100 - Math.Floor(angle * 100)) * 100;
            angle = (d + m / 60 + s / 3600) * 3.1415926 / 180;
            mytps = new svtps(pt, Convert.ToDouble(textBox4.Text));
            mytps.zeroangle = angle;
            ToolClass.SetProfileString("com", Combox.Text);
            ToolClass.SetProfileString("E", pt.E.ToString());
            ToolClass.SetProfileString("N", pt.N.ToString());
            ToolClass.SetProfileString("H", pt.H.ToString());
            ToolClass.SetProfileString("zero", txtzeroangle.Text);
            tabControl1.SelectedIndex = 1;

        }
        #endregion




        #region 第二页
     
     
        int cur_id = -1;
   
        //点击data_config事件
        private void grid_config_Click(object sender, EventArgs e)
        {
            int index = grid_config.CurrentRowIndex;
            if (index < 0)
            {
                return;
            }
            DataTable dt = grid_config.DataSource as DataTable;
            string name = dt.Rows[index][0].ToString();
            txt_new_pt.Text = name;

        }
        //双击data_config事件
        private void grid_config_DoubleClick(object sender, EventArgs e)
        {
            //int index = grid_config.CurrentRowIndex;
            //if (index < 0)
            //{
            //    return;
            //}
            //DataTable dt = grid_config.DataSource as DataTable;
            //dt.Rows.RemoveAt(index);
            //grid_config.DataSource = dt;
        }

        //修改已有的学习点
        private void btnEditPt_Click(object sender, EventArgs e)
        {
            try
            {
                int index = grid_config.CurrentRowIndex;
                if (index < 0)
                {
                    return;
                }
                DataTable dt = grid_config.DataSource as DataTable;
                string name = dt.Rows[index][0].ToString();
                string sql;
                sql="update [dataconfig] set [name]='"+txt_new_pt.Text+
                    "' where [id]=" + cur_id + " and [name]='" + name + "'";
                m_db.ExecuteSQL(sql);
                LoadConfig();
            }
            catch
            {
                MessageBox.Show("修改失败");
            }
        }
        //添加新的学习点
        private void btn_add_pt_Click(object sender, EventArgs e)
        {
            try
            {
                string str = geocom.Measure_Distance_Angle();
                if (!str.Equals("0"))
                {
                   
                    string[] v = str.Split(',');
                    double hv = Convert.ToDouble(v[1]);
                    if (hv > 3.1415926)
                    {
                        MessageBox.Show("请在盘左\r\n进行点学习");
                        return;
                    }
                    svpoint pt = mytps.PolarToXYZ(Convert.ToDouble(v[0]), Convert.ToDouble(v[1]), Convert.ToDouble(v[2]));
                    pt.name = txt_new_pt.Text;
                    string sql = "insert into [dataconfig] values(" + cur_id + ",'" + pt.name + "',"
                        + Math.Round(pt.E, 4) + "," + Math.Round(pt.N, 4) + "," + Math.Round(pt.H, 4) + ")";
                    m_db.ExecuteSQL(sql);
                    sql = "select [name],[E],[N],[H] from [dataconfig] where [id]=" + cur_id;
                    DataTable dt = m_db.GetDataSet(sql).Tables[0];
                    grid_config.DataSource = dt;
                }
                else
                {
                    MessageBox.Show("添加失败");

                }

            }
            catch
            {
                MessageBox.Show("添加失败");
            }
        }

        private void btn_delete_Click(object sender, EventArgs e)
        {
            try
            {
                string name = txt_new_pt.Text;
                string sql = "delete from [dataconfig] where [id]=" + cur_id + " and [name]='" + name + "'";
                m_db.ExecuteSQL(sql);
                sql = "select [name],[E],[N],[H] from [dataconfig] where [id]=" + cur_id;
                DataTable dt = m_db.GetDataSet(sql).Tables[0];
                grid_config.DataSource = dt;

            }
            catch
            {
                MessageBox.Show("删除失败");
            }

        }
        #endregion
        #region index变化
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.TabPages[tabControl1.SelectedIndex].Text == "工程")
            {
                //Load_Projects();
            }
            else if (tabControl1.TabPages[tabControl1.SelectedIndex].Text == "观测")
            {

            }
            else if (tabControl1.TabPages[tabControl1.SelectedIndex].Text == "结果")
            {
                //储存数据
                show_data();
            }
            //else if (tabControl1.SelectedIndex == 4)
            //{
            //    load_pt_names();
            //}
        }
        #endregion

        #region 第三页
        //开始测量
        private void btn_start_Click(object sender, EventArgs e)
        {
            if (comboturn.SelectedIndex < 0)
            {
                MessageBox.Show("测回数不能为空!");
                return;
            }
            try
            {
                stop = false;
                take_turns();
            }
            catch
            {
                parse("碰到异常,结束观测!");
                return;
            }
            //take_turns();

        }
        bool stop = true;
        private void btn_stop_Click(object sender, EventArgs e)
        {
            if (stop == false)
            {
                if (MessageBox.Show("确定要终止观测?", "confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question,MessageBoxDefaultButton.Button1)
                    == DialogResult.Yes)
                {
                    stop = true;
                }
            }
        }
        void parse(string txt)
        {
            txtdata.Text += txt;
            txtdata.SelectionStart = txtdata.Text.Length;
            txtdata.ScrollToCaret();
        }
        void take_turns()
        {
            int count = Convert.ToInt32(comboturn.Text);
            mytps.myturn = new turns();
            mytps.myturn.Count = count;
            mytps.myturn.turn_list = new List<turn>(count);
            mytps.curface = Face.face1;
            
            //如果观测方向大于等于4,则需要归零,于是就加上第一个零方向点
            if (mytps.points.Count >= 4)
            {
                mytps.points.Add(mytps.points[0]);
            }

            //开始测回观测
            for (int i = 0; i < count; i++)
            {
            again:
                
                string msg = string.Empty;
                mytps.curface = Face.face1;
                one_turn_survey(i);
                mytps.curface = Face.face2;
                one_turn_survey(i);
                //在这里归零,检核,等等操作
                bool ok = mytps.myturn.turn_list[i].check(ref msg,mytps.zeroangle);
                if (ok == false)
                {
                    if (MessageBox.Show(msg, "超限", MessageBoxButtons.YesNo, MessageBoxIcon.Question,MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                    {
                        goto again;
                    }
                }

            }
            //bool success = mytps.myturn.check(ref msg);
            //if (success == false)
            //{
            //    MessageBox.Show(msg);
            //    take_turns();
            //}
           // mytps.get_value();
            parse("\r\n观测结束");
            //这时候才开始计算xyz值
           datas = mytps.get_xyz();
        }
        ResultData[] datas;
        void one_turn_survey(int i)
        {
            string msg = string.Empty;
            string cmd = string.Empty;
            string str = string.Empty;
            string face = string.Empty;
            if (mytps.curface == Face.face1)
            {
                face = "正镜";
                turn this_turn = new turn(mytps.points.Count);
                try
                {
                    mytps.myturn.turn_list.Insert(i, this_turn);
                }
                catch
                {

                }
            }
            else
            {
                face = "倒镜";
            }

            List<int> unsurvey = new List<int>();
            for (int j = 0; j < mytps.points.Count; j++)
            {
                try
                {
                    if (mytps.myturn.turn_list[i].pts[j] != null && mytps.myturn.turn_list[i].pts[j].check == true)
                    {
                        continue;
                    }
                }
                catch
                { }
                msg = "第" + (i + 1).ToString() + "测回," + face + ",点名:" + mytps.points[j].name + ":\r\n";
                parse(msg);
                double hz = mytps.getAzim(j);
                double hv = mytps.getVertA(j);
                cmd = hz.ToString() + "," + hv.ToString();
                geocom.Make_Postion(cmd);
                Thread.Sleep(1000);
                Thread.Sleep(600);
                str = geocom.Measure_Distance_Angle();
                Thread.Sleep(1000);
                if (!str.Equals("0"))
                {
                    string[] v = str.Split(',');
                    svpoint p = new svpoint();
                    svpoint pp = new svpoint();
                    if (mytps.curface == Face.face1)//如果是正镜
                    {
                        p.name = mytps.points[j].name;
                        p.Hz1 = Convert.ToDouble(v[0]);
                        p.Hv1 = Convert.ToDouble(v[1]);
                        p.slope1 = Convert.ToDouble(v[2]);
                        p.time1 = DateTime.Now;
                        pp = mytps.PolarToXYZ(p.Hz1, p.Hv1, p.slope1);
                        if (mytps.check_legal(p.slope1, j) == false)//如果检查不合格
                        {
                            msg = "\r\n与学习点差别过大,忽略...\r\n";
                            parse(msg);
                            unsurvey.Add(j);
                            continue;
                        }
                        mytps.myturn.turn_list[i].pts.Add(p);
                    }
                    else//如果是倒镜
                    {
                        try
                        {
                            p.Hz1 = Convert.ToDouble(v[0]);
                            p.Hv1 = Convert.ToDouble(v[1]);
                            p.slope1 = Convert.ToDouble(v[2]);
                            pp = mytps.PolarToXYZ(p.Hz1, p.Hv1, p.slope1);
                            if (mytps.check_legal(p.slope1, j) == false)//如果检查不合格
                            {
                                msg = "\r\n与学习点差别过大,忽略...\r\n";
                                parse(msg);
                                unsurvey.Add(j);
                                continue;
                            }
                            mytps.myturn.turn_list[i].pts[j].Hz2 = Convert.ToDouble(v[0]);
                            mytps.myturn.turn_list[i].pts[j].Hv2 = Convert.ToDouble(v[1]);
                            mytps.myturn.turn_list[i].pts[j].slope2 = Convert.ToDouble(v[2]);
                            mytps.myturn.turn_list[i].pts[j].check = true;
                            mytps.myturn.turn_list[i].pts[j].time2 = DateTime.Now;
                        }
                        catch
                        { }
                    }
                    
                    msg = "E:" + Math.Round(pp.E, 4) + ",N:" + Math.Round(pp.N, 4) + ",H:" + Math.Round(pp.H, 4) + "\r\n";
                    parse(msg);
                }
                else
                {
                    unsurvey.Add(j);
                }
                //if (stop == true)
                //{
                //    parse("用户停止观测");
                //    return;
                //}
            }
            //开始重测
            for (int j = 0; j < unsurvey.Count; j++)
            {
                msg = "重测第" + (i + 1).ToString() + "测回," + face + ",点名:" + mytps.points[unsurvey[j]].name + ":\r\n";
                parse(msg);
                double hz = mytps.getAzim(unsurvey[j]);
                double hv = mytps.getVertA(unsurvey[j]);
                cmd = hz.ToString() + "," + hv.ToString();
                geocom.Make_Postion1(cmd);
                Thread.Sleep(600);
                str = geocom.Measure_Distance_Angle();
                Thread.Sleep(1000);
                if (!str.Equals("0"))
                {
                    string[] v = str.Split(',');
                    svpoint p = new svpoint();
                    if (mytps.curface == Face.face1)
                    {

                        p.name = mytps.points[unsurvey[j]].name;
                        p.Hz1 = Convert.ToDouble(v[0]);
                        p.Hv1 = Convert.ToDouble(v[1]);
                        p.slope1 = Convert.ToDouble(v[2]);
                        p.time1 = DateTime.Now;
                        if (mytps.check_legal(p.slope1, unsurvey[j]) == false)//如果检查不合格
                        {
                            msg = "\r\n与学习点差别过大,放弃...\r\n";
                            parse(msg);
                            if (mytps.curface == Face.face1)
                            {
                                svpoint ag = new svpoint();
                                ag.name = mytps.points[unsurvey[j]].name;
                                mytps.myturn.turn_list[i].pts.Insert(unsurvey[j], ag);
                            }
                            msg = "无法观测到 " + mytps.points[unsurvey[j]].name + " ,放弃...\r\n";
                            parse(msg);
                            continue;
                        }
                        mytps.myturn.turn_list[i].pts.Insert(unsurvey[j], p);
                    }
                    else
                    {
                        p.Hz1 = Convert.ToDouble(v[0]);
                        p.Hv1 = Convert.ToDouble(v[1]);
                        p.slope1 = Convert.ToDouble(v[2]);
                        if (mytps.check_legal(p.slope1, unsurvey[j]) == false)//如果检查不合格
                        {
                            msg = "\r\n与学习点差别过大,放弃...\r\n";
                            parse(msg);
                            continue;
                        }
                        mytps.myturn.turn_list[i].pts[unsurvey[j]].Hz2 = Convert.ToDouble(v[0]);
                        mytps.myturn.turn_list[i].pts[unsurvey[j]].Hv2 = Convert.ToDouble(v[1]);
                        mytps.myturn.turn_list[i].pts[unsurvey[j]].slope2 = Convert.ToDouble(v[2]);
                        mytps.myturn.turn_list[i].pts[unsurvey[j]].check = true;
                        mytps.myturn.turn_list[i].pts[unsurvey[j]].time2 = DateTime.Now;
                    }
                    svpoint pp = mytps.PolarToXYZ(p.Hz1, p.Hv1, p.slope1);
                    msg = "E:" + Math.Round(pp.E, 4) + ",N:" + Math.Round(pp.N, 4) + ",H:" + Math.Round(pp.H, 4) + "\r\n";
                    //msg = "Hv:" + Math.Round(p.Hv1, 7) + ",H:" + Math.Round(pp.H, 4) + "\r\n";
                    parse(msg);
                }
                else//如果实在测不到,就插入个空值.
                {
                   
                    if (mytps.curface == Face.face1)
                    {
                        svpoint p = new svpoint();
                        p.name = mytps.points[unsurvey[j]].name;
                        mytps.myturn.turn_list[i].pts.Insert(unsurvey[j], p);
                    }
                    msg = "无法观测到 " + mytps.points[unsurvey[j]].name + " ,放弃...\r\n";
                    parse(msg);
                }
                //if (stop == true)
                //{
                //    parse("用户停止观测");
                //    return;
                //}
            }

        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            //string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.ToString())
            //    + "\\" + DateTime.Now.ToShortDateString()  + ".txt";
  
            string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.ToString())
                + "\\" + mytps.center.name + "_" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
            using (StreamWriter sw = new StreamWriter(path, true))
            {
                
                string str = "";
                string name = mytps.center.name;
                str = "Station turn ID time1 LHz LHv LSlope time2 RHz RHv RSlope Hz0";
                sw.WriteLine(str);
                for (int i = 0; i < mytps.myturn.turn_list.Count; i++)
                {
                    for (int j = 0; j < mytps.myturn.turn_list[i].pts.Count; j++)
                    {
                        str = name + " " + (i + 1) + " " + mytps.myturn.turn_list[i].pts[j].name + " " + mytps.myturn.turn_list[i].pts[j].time1.ToShortTimeString()
                            + " " + convrt_rag(mytps.myturn.turn_list[i].pts[j].Hz1) + " " + convrt_rag(mytps.myturn.turn_list[i].pts[j].Hv1) + " "
                            + mytps.myturn.turn_list[i].pts[j].slope1 + " " + mytps.myturn.turn_list[i].pts[j].time2.ToShortTimeString() + " "
                            + convrt_rag(mytps.myturn.turn_list[i].pts[j].Hz2) + " " + convrt_rag(mytps.myturn.turn_list[i].pts[j].Hv2) + " " +
                            mytps.myturn.turn_list[i].pts[j].slope2 + " " + convrt_rag(mytps.myturn.turn_list[i].pts[j].Hz0);
                        sw.WriteLine(str);
                    }
                }
               
                txtdata.Text = "";
    
                sw.WriteLine("");
                sw.WriteLine("");
                sw.WriteLine("");
                sw.WriteLine(DateTime.Now.ToString());
                str = "station  ID Hz Hv Dist E N H time";
                sw.WriteLine(str);
                for (int i = 0; i < mytps.myturn.turn_list[0].pts.Count; i++)
                {
                    str = name + " " + mytps.myturn.turn_list[0].pts[i].name +
               " " + mytps.myturn.turn_list[0].pts[i].Hz + " " + mytps.myturn.turn_list[0].pts[i].Hv + " "
                        + mytps.myturn.turn_list[0].pts[i].slope +
                           " " + mytps.myturn.turn_list[0].pts[i].E + " "
                        + mytps.myturn.turn_list[0].pts[i].N + " " + mytps.myturn.turn_list[0].pts[i].H
                        + " " + mytps.myturn.turn_list[0].pts[i].time2.ToString("yyyy-MM-dd hh:mm:ss");
                    sw.WriteLine(str);
                }
                sw.WriteLine("");
                sw.WriteLine("");
                sw.WriteLine("");
                sw.Close();
                txtdata.Text = string.Empty;
                MessageBox.Show("保存文本文件成功");
            }
        }
        //把弧度化成角度string
        string convrt_rag(double rag)
        {
            double d, m, s;
            rag = (rag / 3.1415916) * 180;
            d = Math.Floor(rag);
            rag = (rag - d) * 60;
            m = Math.Floor(rag);
            s = Math.Round((rag - m) * 60, 2);
            return d.ToString() + "." + m.ToString("00") + (s * 10).ToString("000");
        }
        private void btn_clear_Click(object sender, EventArgs e)
        {
            txtdata.Text = string.Empty;
        }
        #endregion

        private void Mfrm_Closed(object sender, EventArgs e)
        {
            try
            {
                if (geocom != null && geocom.port.IsOpen == true)
                {
                    geocom.port.Close();
                }
            }
            catch (Exception a)
            {
                MessageBox.Show(a.Message);
            }
        }

        #region 第四页
        void show_data()
        {
            if (geocom == null || mytps == null || mytps.myturn.turn_list == null || mytps.myturn.turn_list.Count == 0 || mytps.myturn.turn_list[0].pts == null)
            {
                return;
            }
            int cc = mytps.myturn.turn_list[0].pts.Count;
            if (cc == 0)
            {
                return;
            }

            DataTable tt = new DataTable();
            tt.Columns.Add("点名"); tt.Columns.Add("E"); tt.Columns.Add("N"); tt.Columns.Add("H"); 
            for (int i = 0; i < cc; i++)
            {
                object[] para = new object[4];
                para[0]=mytps.myturn.turn_list[0].pts[i].name;
                para[1] = mytps.myturn.turn_list[0].pts[i].E;
                para[2] = mytps.myturn.turn_list[0].pts[i].N;
                para[3] = mytps.myturn.turn_list[0].pts[i].H;
                string sql = "insert into [datalog] values(" + cur_id + ",'" + mytps.myturn.turn_list[0].pts[i].name
                    + "'," + mytps.myturn.turn_list[0].pts[i].Hz + ","
                    + mytps.myturn.turn_list[0].pts[i].Hv +
                    "," + mytps.myturn.turn_list[0].pts[i].slope + ","
                     + mytps.myturn.turn_list[0].pts[i].E + "," +
                      +mytps.myturn.turn_list[0].pts[i].N + "," +
                    +mytps.myturn.turn_list[0].pts[i].H + ",'"
                    + datetime_str(mytps.myturn.turn_list[0].pts[i].time1) + "')";
                tt.Rows.Add(para);
                m_db.ExecuteSQL(sql);
            }
            gird_result.DataSource = tt;
            if (mytps != null)
            {
                mytps.myturn = new turns();
            }
            picker2.Value = DateTime.Now;
            picker1.Value = DateTime.Now.AddDays(-1);
        }

        private void btn_query_Click(object sender, EventArgs e)
        {
            DateTime t1 = picker1.Value;
            DateTime t2 = picker2.Value;
            string sql = "Select [name] as [点名],[E],[N],[H],[time] as [时间],[Hz],[Hv],[slope] as [斜距] from [datalog] where time between '" + datetime_str(t1) + "' and '" +
                datetime_str(t2) + "'";
            DataTable dt = m_db.GetDataSet(sql).Tables[0];
            gird_result.DataSource = dt;
           

        }
        #endregion


        //#region 第五页
        //void load_pt_names()
        //{
        //    //if (cur_id == -1)
        //    //{
        //    //    return;
        //    //}
        //    combo_names.Items.Clear();
        //    string sql = "select [name] from [datalog] where [stationid]=" + cur_id + " group by [name]";
        //    DataTable dt = m_db.GetDataSet(sql).Tables[0];
        //    for (int i = 0; i < dt.Rows.Count; i++)
        //    {
        //        combo_names.Items.Add(dt.Rows[i][0]);
        //    }

        //}
        //#endregion

        //private void combo_names_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    int i = combo_names.SelectedIndex;
        //    if (i < 0)
        //    {
        //        return;
        //    }
        //    string name = combo_names.Items[i].ToString();
        //    string sql = "select [height],[time] from [datalog] where [name]='" + name + "'order by [time]";
        //    DataTable dt = m_db.GetDataSet(sql).Tables[0];
        //    mygraph graph = new mygraph();
        //    Image image = graph.Render(name + "历史曲线", pictureBox1.Width, pictureBox1.Height, dt, name);
        //    pictureBox1.Image = image;

        //}

        private void Mfrm_Deactivate(object sender, EventArgs e)
        {

        }




        private void btnAddPrj_Click_1(object sender, EventArgs e)
        {
            string name = prjNameTxt.Text;
            Add_Project(name);
        }
        #region 添加工程
        //添加工程!!!
        void Add_Project(string prjName)
        {
            string name = prjName;
            if (name == "") return;
            if (IsItemExist(name, "projects", "name") == true) { return; }
            int id = getNewId("projects", "id");
            string sql = "insert into [projects] values('" + datetime_str(DateTime.Now) + "','"
                + name + "'," + id + ")";
            m_db.ExecuteSQL(sql);
            projectsView.Nodes[0].Nodes.Add(name);
        }
        private bool IsItemExist(string name, string table, string column)
        {
            DataTable dt; string sql;
            sql = "select * from [" + table + "] where [" + column + "]='" + name + "'";
            dt = m_db.GetDataSet(sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                MessageBox.Show("该名称已经存在!"); return true;
            }
            else
            {
                return false;
            }
        }
        private bool IsStationItemExist(string name, string table, string column, int prjid)
        {
            DataTable dt; string sql;
            sql = "select * from [" + table + "] where [" + column + "]='" + name
                + "' and [prjid]=" + prjid;
            dt = m_db.GetDataSet(sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                MessageBox.Show("该名称已经存在!"); return true;
            }
            else
            {
                return false;
            }
        }
        //获取应该插入的ID
        private int getNewId(string table, string Column)
        {
            DataTable dt; string sql;
            sql = "select max([" + Column + "])+1 from [" + table + "]";
            dt = m_db.GetDataSet(sql).Tables[0];
            if (dt.Rows.Count == 0)
            {
                return 1;
            }
            else
            {
                try
                {
                    return Convert.ToInt32(dt.Rows[0][0]);
                }
                catch
                {
                    return 1;
                }
            }
      
        }

        private void modifyPrj_Click(object sender, EventArgs e)
        {
            TreeNode n = projectsView.SelectedNode;
            if(n==null) return;
            if (GetNodeLevel(n) != 1)
            {
                MessageBox.Show("没有选择工程!"); return;
            }
            string newName = prjNameTxt.Text;
            string oldName = n.Text;
            UpdateName(oldName, newName, "projects");
            n.Text = newName;
        }
        void UpdateName(string oldName,string newName,string table)
        {
            string sql = "update [" + table + "] set [name]='" + newName + "' where "
                + "[name]='" + oldName + "'";
            m_db.ExecuteSQL(sql);
        }

        private int GetNodeLevel(TreeNode n)
        {
            int level = 0;
            while (n.Parent != null)
            {
                level++;
                n = n.Parent;
            }
            return level;
        }

        private void DeleteProject_Click(object sender, EventArgs e)
        {
            TreeNode n = projectsView.SelectedNode;
            if (n == null) return;
            if (GetNodeLevel(n) != 1)
            {
                MessageBox.Show("没有选择工程!"); return;
            }
            string oldName = n.Text;
            string sql = "delete from [projects] where [name]='" + oldName + "'";
            m_db.ExecuteSQL(sql);
            n.Parent.Nodes.Remove(n);
        }
        #endregion
        #region 测站
        //新建测站
        private void btnaddprj_Click(object sender, EventArgs e)
        {
            string name = stationNameTxt.Text;
            StationTypeFrm frm = new StationTypeFrm();
            frm.ShowDialog();
            if (frm.Isselected == true)
            {
                AddStation(name,frm.TypeStation);
                stationType = frm.TypeStation;
                MessageBox.Show("新建成功");
            }
        }
        private void AddStation(string name,string type)
        {
            if (name == string.Empty)
            {
                MessageBox.Show("工程名称不能为空!");
                return;
            }

            TreeNode n = projectsView.SelectedNode;
            if (n == null) return;
            int level = GetNodeLevel(n);
            int prjId = -999;
            if (level == 0)
            {
                MessageBox.Show("没有选择工程!"); return;
            }
            else if (level == 1)
            {
                prjId = GetPrjIdByName(n.Text);
            }
            else
            {
                prjId = GetPrjIdByName(n.Parent.Text);
            }
            int newStationId = getNewId("stations", "stationid");
            if (IsStationItemExist(name, "stations", "name", prjId) == true) { return; }
            string sql = "insert into [stations] values('" + datetime_str(DateTime.Now) + "','"
      + name + "'," + newStationId + "," + prjId + ",'" + type + "')";
            m_db.ExecuteSQL(sql);
            cur_id = newStationId;
            grid_config.DataSource = null;
            if (level == 1)
            {
                n.Nodes.Add(name);
            }
            if (level == 2)
            {
                n.Parent.Nodes.Add(name);
            }
        }
        private int GetPrjIdByName(string name)
        {
            string sql = "select [id] from [projects] where [name]='" + name + "'";
            return Convert.ToInt32(m_db.GetDataSet(sql).Tables[0].Rows[0][0]);
        }
        private void modifyStation_Click(object sender, EventArgs e)
        {
            TreeNode n = projectsView.SelectedNode;
            if (n == null) return;
            if (GetNodeLevel(n) != 2)
            {
                MessageBox.Show("没有选择测站!"); return;
            }
            StationTypeFrm frm = new StationTypeFrm();
            frm.ShowDialog();
            if (frm.Isselected == true)
            {
                string sql = "update [stations] set [type]='" + frm.TypeStation + "' where [name]='"
                    + n.Text + "'";
                m_db.ExecuteSQL(sql);
                stationType = frm.TypeStation;
            }
            string newName = stationNameTxt.Text;
            string oldName = n.Text;
            UpdateName(oldName, newName, "stations");
            n.Text = newName;
        }

        private void DeleteStation_Click(object sender, EventArgs e)
        {
            TreeNode n = projectsView.SelectedNode;
            if (n == null) return;
            if (GetNodeLevel(n) != 2)
            {
                MessageBox.Show("没有选择测站!"); return;
            }
            string oldName = n.Text;
            string sql = "delete from [stations] where [name]='" + oldName + "'";
            m_db.ExecuteSQL(sql);
            n.Parent.Nodes.Remove(n);
            MessageBox.Show("删除成功!");
        }
        #endregion

        #region 上下调动Station
        private void btnStUtionp_Click(object sender, EventArgs e)
        {
            GoUp(true);
        }
        private void btnStationDown_Click(object sender, EventArgs e)
        {
            GoUp(false);
        }
        void GoUp(bool isup)
        {
            TreeNode n = projectsView.SelectedNode;
            if (n == null) return;
            if (GetNodeLevel(n) != 2)
            {
                MessageBox.Show("没有选择测站!"); return;
            }
            TreeNode ParentNode = projectsView.Nodes[0];
            int OldPrjId = GetPrjIdByName(n.Parent.Text);
            int parentIndex = ParentNode.Nodes.IndexOf(n.Parent);
            //移除
            ParentNode.Nodes[parentIndex].Nodes.Remove(n);
            if (isup == true)
            {
                if (parentIndex == 0)
                {
                    return;
                }
                parentIndex--;
            }
            else
            {
                if (parentIndex == ParentNode.Nodes.Count - 1)
                {
                    return;
                }
                parentIndex++;
            }
            string newProjectName = ParentNode.Nodes[parentIndex].Text;
            int NewPrjId = GetPrjIdByName(newProjectName);
            string sql = "update [stations] set [prjid]=" + NewPrjId
                + " where [prjid]=" + OldPrjId + " and [name]='" + n.Text + "'";
            m_db.ExecuteSQL(sql);
            //添加
            ParentNode.Nodes[parentIndex].Nodes.Add(n);
            projectsView.SelectedNode = n;
        }
        #endregion

        private void projectsView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode n = projectsView.SelectedNode;
            if (n == null) return;
            int level = GetNodeLevel(n);
            if (level ==1 )
            {
                prjNameTxt.Text = n.Text;
            }
            else if (level == 2)
            {
                prjNameTxt.Text = n.Parent.Text;
                stationNameTxt.Text = n.Text;
                int prjId = GetPrjIdByName(n.Parent.Text);
                LoadStationConfig(prjId, n.Text);
            }
        }
        string stationType;
        void LoadStationConfig(int prjid,string stationName)
        {
            string sql = "select [stationid],[type] from [stations] where [name]='"
                + stationName + "' and [prjid]=" + prjid;
            DataTable dt = m_db.GetDataSet(sql).Tables[0];
            int id = Convert.ToInt32(dt.Rows[0][0]);
            stationType = dt.Rows[0][1].ToString();
            cur_id = id;
            if (mytps != null)
            {
                mytps.center.name = stationName;
            }
            LoadConfig();
        }
        void LoadConfig()
        {
            string sql = "select [name],[E],[N],[H] from [dataconfig] where [id]=" + cur_id;
            DataTable dt = m_db.GetDataSet(sql).Tables[0];
            grid_config.DataSource = dt;
            if (dt.Rows.Count == 0)
            {
                return;
            }
            else if (mytps != null)
            {
                mytps.points = new List<svpoint>(dt.Rows.Count);

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    svpoint pt = new svpoint(dt.Rows[i][0].ToString(), Convert.ToDouble(dt.Rows[i][1]), Convert.ToDouble(dt.Rows[i][2]),
                        Convert.ToDouble(dt.Rows[i][3]));
                    mytps.points.Add(pt);
                }
            }
        }

        private void 平面位移观测_Load(object sender, EventArgs e)
        {
            Load_Projects();
           
        }

        private void btnorientation_Click(object sender, EventArgs e)
        {
            double angle = Convert.ToDouble(txtzeroangle.Text);
            double d = Math.Floor(angle);
            double m = Math.Floor((angle - d) * 100);
            double s = (angle * 100 - Math.Floor(angle * 100)) * 100;
            angle = (d + m / 60 + s / 3600) * 3.1415926 / 180;
            geocom.Set_Orientaion(angle.ToString());
        }

        int remoteId = -1;
        //上传测站
        private void button1_Click(object sender, EventArgs e)
        {
            if (stationNameTxt.Text.Length == 0) return;
            DataTransferClient client = new DataTransferClient();
            remoteId = client.InsertNewStationId(stationNameTxt.Text,stationType);
            ToolClass.SetProfileString("remoteid", remoteId.ToString());
            ToolClass.SetProfileString("stationid", cur_id.ToString());
            ToolClass.SetProfileString("pdaName", stationNameTxt.Text);
            MessageBox.Show("成功!");
        }


        //上传学习点
        private void button2_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("上传将覆盖服务器数据", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1) != DialogResult.OK)
            {
                return;
            }
            LoadConfig();
            if (mytps.points.Count == 0) return;
            DataTransferClient client = new DataTransferClient();
            if (client.SaveConfigPoints(mytps.GetConfigPointData(), remoteId))
            {
                MessageBox.Show("成功!");
            }
            else
            {
                MessageBox.Show("失败,检查网络!");
            }
        }

        //储存观测点
        private void btn_save_process_Click(object sender, EventArgs e)
        {
            DataTransferClient client = new DataTransferClient();
            if (client.SavePoints(datas, remoteId, client.GetNewNo(remoteId)))
            {
                MessageBox.Show("成功!");
            }
            else
            {
                MessageBox.Show("失败,检查网络!");
            }
        }


        //下载数据到本地
        private void button3_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("下载将覆盖本地数据", "提示", MessageBoxButtons.OKCancel,MessageBoxIcon.Exclamation,MessageBoxDefaultButton.Button1) == DialogResult.OK)
            {
                GetConfigPointsFromRemoteDataBase();
            }
        }
        private void GetConfigPointsFromRemoteDataBase()
        {
           
            {
                DataTransferClient client = new DataTransferClient();
                PointData[] remotedatas = client.GetConfigPoints(remoteId);
                string sql = "delete from [dataconfig] where [id]=" + cur_id;
                m_db.ExecuteSQL(sql);
               
                foreach (PointData d in remotedatas)
                {
                    SaveConfigInlocal(d);
                }
                LoadConfig();
            }
        }
        private void SaveConfigInlocal(PointData d)
        {
            string sql = "insert into [dataconfig] values(" + cur_id + ",'" + d.Name + "',"
                 + d.E + "," + d.N + "," + d.H + ")";
            m_db.ExecuteSQL(sql);
        }
    }
}